package com.demo.oauth2jFinalShiroClient.web;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.URLConnectionClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthAccessTokenResponse;
import org.apache.oltu.oauth2.client.response.OAuthAuthzResponse;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.message.types.GrantType;

import com.demo.oauth2jFinalShiroClient.config.HomeOAuth2Config;
import com.demo.oauth2jFinalShiroClient.config.OAuth2Config;
import com.jfinal.core.ActionKey;
import com.jfinal.core.Controller;

public class OAuth2ClientController extends Controller {

	//用于接收客户端code，然后发请求获取token
	@ActionKey("/oauth2/callBack")
	public void callBack() {
		HttpServletRequest request = getRequest();
		try {
			OAuthAuthzResponse oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);
			String code = oar.getCode();
			String state = oar.getState();
			if (!StringUtils.isEmpty(code) 
					&& !StringUtils.isEmpty(state)
					&& state.equals(getSessionAttr(HomeOAuth2Config.OAUTH_STATE_SESSION_ATTR_NAME))) {
				OAuth2Config config = HomeOAuth2Config.STATE_CONFIG_MAP.get(oar.getState());
				
				//申请access_token令牌
			    OAuthClientRequest accessTokenRequest = OAuthClientRequest
			            .tokenLocation(config.getServerAccessTokenUrl())
			            .setGrantType(GrantType.AUTHORIZATION_CODE)
			            .setClientId(config.getOauthClientId())
			            .setClientSecret(config.getOauthClientSecret())
			            .setCode(code)
			            .setRedirectURI(HomeOAuth2Config.CLIENT_CODE_CALLBACK_URL)
			            .buildQueryMessage();
			    OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());	            
			    OAuthAccessTokenResponse oAuthResponse = oAuthClient.accessToken(accessTokenRequest, OAuthJSONAccessTokenResponse.class);
			    
			    //通过令牌获取用户基本信息
			    String accessToken = oAuthResponse.getAccessToken();
				if (!StringUtils.isEmpty(accessToken)) {
					setSessionAttr(HomeOAuth2Config.OAUTH_ACCESS_TOKEN_SESSION_ATTR_NAME, accessToken);
					setSessionAttr(HomeOAuth2Config.OAUTH_CONFIG_SESSION_ATTR_NAME, config);
					redirect(config.getClientUserinfoUrl());
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		redirect("/index.jsp");
	}
	
}
